﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace DevTools.BatchRenamer.Forms
{
    public partial class BatchRenamerForm : XtraForm
    {
        public BatchRenamerForm()
        {
            InitializeComponent();
        }

        private readonly List<FileInfo> _files = new List<FileInfo>();

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            btnBrowse.PerformClick();
        }

        private void CollectFiles(DirectoryInfo directory)
        {
            _files.AddRange(directory.GetFiles("*.*"));

            foreach (var item in directory.GetDirectories())
                CollectFiles(item);
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (fbdBrowse.ShowDialog() == DialogResult.OK)
            {
                txeBrowse.Text = fbdBrowse.SelectedPath;
                
                CollectFiles(new DirectoryInfo(fbdBrowse.SelectedPath));

                StringBuilder builder = new StringBuilder();
                foreach (var file in _files)
                    builder.AppendLine(file.Name);

                mmeSource.Text = builder.ToString();
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            var lines = mmeTarget.Text.Split(new[] {Environment.NewLine}, StringSplitOptions.None);

            for (int i = 0; i < _files.Count; i++)
            {
                string path = _files[i].DirectoryName + "\\" + lines[i];
                _files[i].MoveTo(path);
            }
        }
    }
}